package cn.sh.library.gmwx.sparql.impl;

import java.util.Map;

import javax.annotation.Resource;

import org.ontoware.rdf2go.model.Model;
import org.ontoware.rdf2go.model.QueryResultTable;
import org.ontoware.rdf2go.model.QueryRow;
import org.springframework.stereotype.Repository;

import cn.sh.library.gmwx.annotation.GraphDefine;
import cn.sh.library.gmwx.base.Constant;
import cn.sh.library.gmwx.bean.OrganizationSearchBean;
import cn.sh.library.gmwx.common.ModelManager;
import cn.sh.library.gmwx.config.AppConfig;
import cn.sh.library.gmwx.dao.impl.BaseDaoImpl;
import cn.sh.library.gmwx.dto.QueryResult;
import cn.sh.library.gmwx.sparql.BaseinfoSparql;
import cn.sh.library.gmwx.sparql.MergeParts;
import cn.sh.library.gmwx.sparql.OrganizationSparql;
import cn.sh.library.gmwx.sparql.RdfQuery;
import cn.sh.library.gmwx.sparql.SparqlExecution;
import cn.sh.library.gmwx.utils.RDFUtils;

@Repository
@GraphDefine(name = Constant.GRAPH_ORGANIZATION)
public class OrganizationSparqlImpl extends BaseDaoImpl implements OrganizationSparql {
    @Resource
    private AppConfig appConfig;

    @Override
    public QueryResult<Map<String, String>> searchOrgs(OrganizationSearchBean search, String order, int start, int size) {
        Model model_op = ModelManager.get(getModel(Constant.GRAPH_ORGANIZATION));

        String clause = MergeParts.organizationSearch(search);

        QueryResultTable rst = model_op.sparqlSelect(RdfQuery.RDF_COUNT_ORG_Q.toString(clause));

        Long count = null;

        for(QueryRow row : rst) {
            count = Long.parseLong(RDFUtils.getValue(row.getLiteralValue("count")));
        }

        QueryResult<Map<String, String>> result = new QueryResult<>();
        result.setTotalrecord(count);
        if(count > 0) {
            rst = model_op.sparqlSelect(RdfQuery.RDF_QUERY_ORG_Q.toString(clause, order, start, size));
            result.setResultList(RDFUtils.transformQueryResultTable(rst));
        }

        return result;
    }
}
